#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
void CountSort1(int* a, int n)
{
	int max = a[0];
	int min = a[0];
	for (int i = 1; i < n; i++)
	{
		if (a[i] > max)
		{
			max = a[i];
		}
		if (a[i] < min)
		{
			min = a[i];
		}
	}

	int range1 = max - min + 1;
	printf("range1:%d\n", range1);

	int* count = (int*)calloc(range1, sizeof(int));
	if (count == NULL)
	{
		perror("calloc failed");
		exit(-1);
	}

	//统计数据出现的个数
	for (int i = 0; i < n; i++)
	{
		count[a[i] - min]++;
	}

	//排序
	int j = 0;
	for (int i = 0; i < range1; i++)
		while (count[i]--)
		{
			a[j] = i + min;
			j++;
		}
}
void CountSort2(int* a, int n)
{
	int min = a[0], max = a[0];
	for (size_t i = 0; i < n; i++)
	{
		if (a[i] < min)
			min = a[i];

		if (a[i] > max)
			max = a[i];
	}

	int range2 = max - min + 1;
	int* count = (int*)malloc(sizeof(int) * range2);
	printf("range:%d\n", range2);
	if (count == NULL)
	{
		perror("malloc fail");
		return;
	}
	memset(count, 0, sizeof(int) * range2);

	// 统计数据出现次数
	for (int i = 0; i < n; i++)
	{
		count[a[i] - min]++;
	}

	// 排序
	int j = 0;
	for (int i = 0; i < range2; i++)
	{
		while (count[i]--)
		{
			a[j++] = i + min;
		}
	}
}
void TestOP()
{
	srand(time(0));
	const int N = 10000000;
	int* a1 = (int*)malloc(sizeof(int) * N);
	int* a2 = (int*)malloc(sizeof(int) * N);

	for (int i = N - 1; i >= 0; --i)
	{
		a1[i] = rand() + i;
		a2[i] = a1[i];
	}

	int begin1 = clock();
	CountSort1(a1, N);
	int end1 = clock();

	int begin2 = clock();
	CountSort2(a2, N);
	int end2 = clock();

	printf("CountSort1:%d\n", end1 - begin1);
	printf("CountSort2:%d\n", end2 - begin2);

	free(a1);
	free(a2);

}
int main()
{
	TestOP();

	return 0;
}